package io.github.biezhi.elves.service.impl;

import java.net.URLEncoder;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import io.github.biezhi.elves.common.Constants;
import io.github.biezhi.elves.common.MapConstants;
import io.github.biezhi.elves.model.EbaseInfo;
import io.github.biezhi.elves.model.FamilyInvestmentInfo;
import io.github.biezhi.elves.model.LegalInfo;
import io.github.biezhi.elves.service.FamilyInvestmentService;
import io.github.biezhi.elves.service.ShareholderService;
import io.github.biezhi.elves.utils.HttpUtil;
import io.github.biezhi.elves.utils.StringUtils;

/**
 * 投资族谱业务接口实现类
 *
 */
@Service("familyInvestmentService")
public class FamilyInvestmentServiceImpl implements FamilyInvestmentService {
	
	@Autowired
	private ShareholderService shareholderService;
	

	/**
	 * 获取投资族谱KeyNo的uuid
	 * @return
	 */
	private String getFamilyInvestmentKeyNoUUID(){
		//获取uuid
		String uuid = StringUtils.get32UUID();
		while(true){
			//将uuid作为入参，查询投资族谱表数据keyno值，是否已存在数据库中，如果存在，则重新获取，不存在，则直接返回
			int existCount = shareholderService.countFamilyInvestmentKeyNoByUuid(uuid);
			if(existCount>0){
				//重新获取uuid
				uuid = StringUtils.get32UUID();
			}else{
				break;
			}
		}
		return uuid;
	}
	
	/**
	 * 解析json数据并保存投资族谱数据入库
	 * @param cmsAsynUrl
	 * @param jsonStr
	 * @param unique
	 * @param entname
	 * @param requestEntnameVal
	 */
	public void saveFamilyInvestmentData(String cmsAsynUrl,String jsonStr,String unique,String entname,String requestEntnameVal){
		String resultJson = "";
		String parentKeyNo = "";
		boolean isChildren = false;
		try {
			JSONObject json = JSONObject.parseObject(jsonStr);
			if(json.containsKey("Result")){
				resultJson = json.getString("Result");
				
				JSONObject nodeJson = JSONObject.parseObject(resultJson);
				if(nodeJson.containsKey("Node")){
					resultJson = nodeJson.getString("Node");
				}
			}else{
				resultJson = json.getString("children");
			}
			JSONObject resultJsonObject = JSONObject.parseObject(resultJson);
			FamilyInvestmentInfo familyInvestmentInfo = null;
			List<EbaseInfo> ebaseInfoList = shareholderService.queryEbaseInfoByEntname(entname);
			if(ebaseInfoList!=null && ebaseInfoList.size()>0){
				for(EbaseInfo ebaseInfo : ebaseInfoList){
					familyInvestmentInfo = JSON.parseObject(resultJson, FamilyInvestmentInfo.class);
					
					if(!StringUtils.isNullOrEmpty(unique)){
						familyInvestmentInfo.setUniqueId(unique);
					}
					familyInvestmentInfo.setPripid(ebaseInfo.getPripid());
					//企业名称
					if(resultJsonObject.containsKey("name")){
						familyInvestmentInfo.setEntname(resultJsonObject.getString("name"));
					}
					if(!isChildren){
						if(resultJsonObject.containsKey("KeyNo")){
							parentKeyNo = resultJsonObject.getString("KeyNo");
						}else{
							parentKeyNo = getFamilyInvestmentKeyNoUUID();
						}
						familyInvestmentInfo.setParentKeyNo("0");
					}else{
						familyInvestmentInfo.setParentKeyNo(parentKeyNo);
					}
					//地市Id
					familyInvestmentInfo.setCityId(ebaseInfo.getCityId());
					System.out.println("非循环体{{}}==>json转换对象数据{{}}==>" + familyInvestmentInfo);
					//保存投资族谱
					shareholderService.saveFamilyInvestmentInfo(familyInvestmentInfo);
				}
			}else{
				familyInvestmentInfo = JSON.parseObject(resultJson, FamilyInvestmentInfo.class);
				
				if(!StringUtils.isNullOrEmpty(unique)){
					familyInvestmentInfo.setUniqueId(unique);
				}
				//企业名称
				if(resultJsonObject.containsKey("name")){
					familyInvestmentInfo.setEntname(resultJsonObject.getString("name"));
				}
				if(!isChildren){
					if(resultJsonObject.containsKey("KeyNo")){
						parentKeyNo = resultJsonObject.getString("KeyNo");
					}else{
						parentKeyNo = getFamilyInvestmentKeyNoUUID();
					}
					familyInvestmentInfo.setParentKeyNo("0");
				}else{
					familyInvestmentInfo.setParentKeyNo(parentKeyNo);
				}
				System.out.println("非循环体{{}}==>json转换对象数据{{}}==>" + familyInvestmentInfo);
				//保存投资族谱数据
				shareholderService.saveFamilyInvestmentInfo(familyInvestmentInfo);
			}
			
			String childrenKeyNo = "";
			String childrenParentKeyNo = "";
			if(resultJsonObject.containsKey("children") && resultJsonObject.get("children")!=null){
				JSONArray array = resultJsonObject.getJSONArray("children");
				for (int i = 0; i < array.size(); i++) {
					JSONObject arrJsonObject = array.getJSONObject(i);
					String arrJsonStr = arrJsonObject.toJSONString();
					JSONObject childrenJsonObject = JSONObject.parseObject(arrJsonStr);
					familyInvestmentInfo = JSON.parseObject(arrJsonStr, FamilyInvestmentInfo.class);
					if(!StringUtils.isNullOrEmpty(unique)){
						familyInvestmentInfo.setUniqueId(unique);
					}
					//企业名称
					if(childrenJsonObject.containsKey("name")){
						familyInvestmentInfo.setEntname(childrenJsonObject.getString("name"));
					}
					if(!childrenJsonObject.containsKey("KeyNo")){
						childrenKeyNo = getFamilyInvestmentKeyNoUUID();
						childrenParentKeyNo = childrenKeyNo;
						familyInvestmentInfo.setKeyNo(childrenKeyNo);
						familyInvestmentInfo.setParentKeyNo(parentKeyNo);
					}else{
						childrenParentKeyNo = childrenJsonObject.getString("KeyNo");
						familyInvestmentInfo.setParentKeyNo(parentKeyNo);
					}
					System.out.println("循环体{{}}==>json转换对象数据{{}}==>" + familyInvestmentInfo);
					//保存投资族谱数据
					shareholderService.saveFamilyInvestmentInfo(familyInvestmentInfo);
				    if(arrJsonObject.containsKey("children") && (arrJsonObject.get("children")!=null || !"null".equals(arrJsonObject.get("children").toString()))){
				    	//解析投资族谱子json数据
				    	saveFamilyInvestmentChildrenData(arrJsonObject.get("children").toString(),unique,entname,childrenParentKeyNo);
				    }
				}
			}
		} catch (Exception e) {
			System.err.println("io.github.biezhi.elves.spider.saveFamilyInvestmentData，解析json数据并保存投资族谱数据入库异常，cmsAsynUrl链接为:" + cmsAsynUrl + "，json串为:" + jsonStr + "，异常信息{{}}==>" + StringUtils.getErrorInfoFromException(e));
			
			System.out.println("io.github.biezhi.elves.spider.saveFamilyInvestmentData，休眠5000毫秒后，重新再调用......");
			try {
				Thread.sleep(5000);
				System.out.println("io.github.biezhi.elves.spider.saveFamilyInvestmentData，已休眠5000毫秒，开始重新再调用saveFamilyInvestmentData方法===>");
				System.err.println("企业名称{{}}==>" + entname);
				//返回响应url内容
				jsonStr = HttpUtil.getQccGetHttpReponseBody(cmsAsynUrl);
				saveFamilyInvestmentData(cmsAsynUrl,jsonStr, unique, entname, requestEntnameVal);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
		}
	}
	
	/**
	 * 解析投资族谱子json数据
	 * @param jsonStr
	 * @param unique
	 * @param entname
	 * @param childrenParentKeyNo
	 */
	public void saveFamilyInvestmentChildrenData(String jsonStr,String unique,String entname,String childrenParentKeyNo){
		try{
			JSONArray array = JSONArray.parseArray(jsonStr);
			if(array!=null){
				for (int i = 0; i < array.size(); i++) {
					JSONObject arrJsonObject = array.getJSONObject(i);
					String arrJsonStr = arrJsonObject.toJSONString();
					JSONObject childrenJsonObject = JSONObject.parseObject(arrJsonStr);
					
					FamilyInvestmentInfo familyInvestmentInfo = JSON.parseObject(arrJsonStr, FamilyInvestmentInfo.class);
					if(!StringUtils.isNullOrEmpty(unique)){
						familyInvestmentInfo.setUniqueId(unique);
					}
					//企业名称
					if(childrenJsonObject.containsKey("name")){
						familyInvestmentInfo.setEntname(childrenJsonObject.getString("name"));
					}
					if(!childrenJsonObject.containsKey("KeyNo")){
						String childrenKeyNo = getFamilyInvestmentKeyNoUUID();
						familyInvestmentInfo.setKeyNo(childrenKeyNo);
						familyInvestmentInfo.setParentKeyNo(childrenParentKeyNo);
					}else{
						familyInvestmentInfo.setParentKeyNo(childrenParentKeyNo);
					}
					System.out.println("子循环体{{}}==>json转换对象数据{{}}==>" + familyInvestmentInfo);
					try {
						//保存投资族谱数据
						shareholderService.saveFamilyInvestmentInfo(familyInvestmentInfo);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}catch(Exception e){
			System.err.println("io.github.biezhi.elves.spider.saveFamilyInvestmentChildrenData，解析子json数据并保存投资族谱数据入库异常，json串为:" + jsonStr + "{{}}==>" + StringUtils.getErrorInfoFromException(e));
			
			System.out.println("io.github.biezhi.elves.spider.saveFamilyInvestmentChildrenData，休眠5000毫秒后，重新再调用......");
			try {
				Thread.sleep(5000);
				
				System.out.println("io.github.biezhi.elves.spider.saveFamilyInvestmentChildrenData，已休眠5000毫秒，开始重新再调用saveFamilyInvestmentChildrenData方法===>");
				saveFamilyInvestmentChildrenData(jsonStr, unique, entname, childrenParentKeyNo);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
		}
	}
	
	/**
	 * 补充投资族谱数据
	 * @param pageNum
	 * @param cityId
	 */
	@SuppressWarnings("deprecation")
	public void supplementFamilyInvestmentInfoData(int pageNum, String cityId) {
		try{
			int updatePageSize = Constants.UPDATE_PAGE_SIZE;
			System.out.println(this.getClass() + ".supplementFamilyInvestmentInfoData[{}]==>当前页数:" + pageNum + "，每页显示记录数:" + updatePageSize);
			//获取法人代表数据(分页)
			List<LegalInfo> legalInfoPageList = shareholderService.getLegalInfoPageByCityId(pageNum,updatePageSize,cityId);
			if(legalInfoPageList!=null && legalInfoPageList.size() > 0) {
				int index = 0;
				for(LegalInfo legalInfo : legalInfoPageList) {
					
					index++;
					
					String entname = legalInfo.getEntname();
					System.out.println("======开始新增第" + index + "条，" + entname + "投资族谱数据=====");
					System.out.println();
					
					String requestEntnameVal = URLEncoder.encode(entname);
					String uniqueId = legalInfo.getUniqueId();
					//投资族谱链接
					String cmsAsynUrl = StringUtils.getValueForKey("cms_map", MapConstants.QCC_REQUEST_URL_MAP) + uniqueId;
					//返回响应url内容
					String jsonStr = StringUtils.getQccGetHttpForJsonData(cmsAsynUrl,requestEntnameVal);
					if(!StringUtils.isNullOrEmpty(jsonStr)){
						try{
							JSONObject json = JSONObject.parseObject(jsonStr);
							String status = json.getString("Status");
							if(json.containsKey("Status") && "200".equals(status)){
								//解析json数据并保存投资族谱数据入库
								saveFamilyInvestmentData(cmsAsynUrl,jsonStr,uniqueId,entname,requestEntnameVal);
							}else{
								System.err.println("投资族谱Status状态值非200，状态值为{{}}==>" + status + "，企业名称{{}}==>" + entname + "，json串{{}}==>" + jsonStr);
							}
						}catch(Exception e){
							System.out.println("处理投资族谱数据异常{{}}==>" + StringUtils.getErrorInfoFromException(e));
						}
					}
				}
				
				//查询投资族谱表总数
				int countEnterpriseProfile = shareholderService.countFamilyInvestmentInfo("4401");
				System.err.println("共要补充数据量为{{}}==>" + legalInfoPageList.size());
				System.err.println("已补充投资族谱数据量{{}}==>" + countEnterpriseProfile);
			} else {
				System.out.println();
				System.out.println("======已完成投资族谱数据补充，系统自动停止======");
				System.exit(0);
			}
		}catch(Exception e){
			System.out.println("投资族谱解析json数据异常{{}}==>" + e.getMessage());
		}
	}
}